/**
 * Our custom rollup plugin, a wrapper for server-io-core
 */
import serverIoCore from 'server-io-core'
/**
 * @param {object} options pass to server-io-core
 * @return {object} for rollup
 */
export default function serverIo(options = {}) {
  // Force these options on config
  const config = Object.assign(options, {
    autoStart: false, // we must overwrite this for the plugin to work
    reload: {
      enable: true,
      verbose: false
    }
  })
  // getting the fn(s)
  const { start, stop } = serverIoCore(config)
  const signals = ['SIGINT', 'SIGTERM']
  // listen to signal and close it
  signals.forEach(signal => {
    process.on(signal, () => {
      stop()
      process.exit()
    })
  })
  let running
  // return
  return {
    name: 'serverIo',
    buildEnd() {
      if (!running) {
        running = true
        start()
      }
    }
  }
}
